<?php
// +----------------------------------------------------------------------
// | INPHP
// | Copyright (c) https://inphp.cc All rights reserved.
// | 该文件源码由INPHP官方提供，使用协议以INPHP官方公告为准。
// +----------------------------------------------------------------------
// | 在线充值
// +----------------------------------------------------------------------
namespace app\finance\http\api;

use app\admin\attributes\auth;
use app\finance\model\BalanceModel;
use app\finance\model\CashierModel;
use app\finance\model\RechargeModel;
use app\sso\model\UserModel;
use Inphp\Core\Db\PDO\Query;
use Inphp\Core\Modules;
use Inphp\Core\Object\Message;
use Inphp\Core\Util\Str;

#[auth] class recharge
{
    public int $uid = 0;

    public array $user = [
        "admin" => 0
    ];

    public function index(?array $params = null): Message
    {
        $sso = Modules::getModule("sso");
        if (!$sso) {
            return httpMessage("缺少SSO模块");
        }
        $params = $params ?? getClient()->get;
        $orderId = $params["orderId"] ?? 0;
        $orderId = is_numeric($orderId) && $orderId > 0 ? $orderId : 0;
        if ($orderId <= 0) {
            return httpMessage("订单号无效");
        }
        $db = RechargeModel::emptyQuery("r")
            ->join(UserModel::as("u"), "r.uid=u.uid")
            ->where("r.orderId", $orderId)
            ->select([
                "r.*",
                "u.username, u.nickname, u.countryCode, u.phone"
            ]);
        $admin = $params["admin"] ?? 0;
        $admin = $admin == 1 ? 1 : 0;
        $admin = $admin == 1 && ($this->user["admin"] == 1 || (!empty($this->user["groups"]) && \app\sso\model\UserModel::matchPermission(["finance/recharge"], $this->user["groups"])));
        if (!$admin) {
            $db->where("r.uid", $this->uid);
        }
        $item = $db->first();
        if (empty($item)) {
            return httpMessage("未找到数据");
        }
        $item['nickname'] = \app\sso\model\UserModel::decodeNickname($item['nickname']);
        $item["paymentName"] = CashierModel::getPayment($item["payment"]);
        $item["balanceName"] = $balanceNames[$item["balance"]] ?? "未知";
        $item["balanceUnit"] = CashierModel::currencyUnit($item["balance"]);
        $item["canRefund"] = $item["payedAmount"] - $item["refundAmount"] > 0 ? 1 : 0;
        return httpMessage($item);
    }

    public function list(?array $params = null): array
    {
        $params = $params ?? getClient()->get;
        $admin = $params["admin"] ?? 0;
        $admin = $admin == 1 ? 1 : 0;
        $sso = Modules::getModule("sso");
        if (!$sso) {
            return [
                "rows"      => 0,
                "page"      => 1,
                "pages"     => 0,
                "list"      => []
            ];
        }
        //判断是不是管理员
        $admin = $admin == 1 && ($this->user["admin"] == 1 || ($sso && !empty($this->user["groups"]) && \app\sso\model\UserModel::matchPermission(["finance/recharge"], $this->user["groups"])));
        $db = RechargeModel::emptyQuery("r")
            ->join(UserModel::as("u"), "r.uid=u.uid")
            ->select([
                "r.*",
                "u.username, u.nickname, u.countryCode, u.phone"
            ]);
        //非管理模式，仅获取自己账号的
        if (!$admin) {
            $db->where("r.uid", $this->uid);
        }
        //是否已支持
        $payed = $params["payed"] ?? '';
        if ($payed == 1 || $payed == '0') {
            $db->where("r.payed", $payed);
        }
        $payments = CashierModel::payments();
        //支付方式
        $payment = $params["payment"] ?? '';
        $payment = !empty($payment) ? trim($payment) : null;
        if (!empty($payment) && in_array($payment, array_keys($payments))) {
            $db->whereFindInSet($payment, "r.payment");
        }
        //是否有退款
        $refund = $params["refund"] ?? '';
        if ($refund == 1 || $refund == '0') {
            $db->where("r.refund", $refund);
        }
        //搜索
        $keyword = $params["keyword"] ?? '';
        $keyword = !empty($keyword) ? Str::trim($keyword) : null;
        if (!empty($keyword)) {
            if ($sso && $admin) {
                if (is_numeric($keyword) && strlen($keyword) < 12) {
                    //数字，查询手机号码
                    $db->where(function (Query $q) use ($keyword) {
                        $q->whereLike("u.phone", $keyword)
                            ->orWhereLike("r.orderId", $keyword);
                    });
                } else {
                    //其它，查询昵称
                    $db->where(function(Query $q) use($keyword) {
                        $q->whereLike("u.username", $keyword)
                            ->orWhereLike("from_base64(substr(u.nickname, 23))", $keyword);
                    });
                }
            } else {
                $db->whereLike("r.orderId", $keyword);
            }
        }
        //行数
        $rows = $db->rows();
        //当前页数
        $page = $params['page'] ?? 1;
        $page = is_numeric($page) && $page > 0 ? ceil($page) : 1;
        //总页数
        $pages = 1;
        //列表数据
        $list = [];
        if ($rows > 0) {
            $total = $params["total"] ?? 30;
            $total = is_numeric($total) && $total > 2 ? $total : 30;
            $pages = ceil($rows / $total);
            $page = $page > $pages ? $pages : $page;
            $offset = $total * ($page - 1);
            $list = $db->orderBy("r.time", "desc")->get($total, $offset);
            $balanceNames = getFinanceConfig("balance.list");
            foreach ($list as &$item)
            {
                $item['nickname'] = \app\sso\model\UserModel::decodeNickname($item['nickname']);
                $item["paymentName"] = !empty($item["payment"]) ? CashierModel::getPayment($item["payment"]) : '-';
                $item["balanceName"] = $balanceNames[$item["balance"]] ?? "未知";
                //$item["balanceUnit"] = CashierModel::currencyUnit($item["balance"]);
                $item["canRefund"] = $item["payedAmount"] - $item["refundAmount"] > 0 ? 1 : 0;
            }
        }
        return compact("rows", "page", "pages", "list");
    }

    public function submit(): Message
    {
        if ($this->uid <= 0) {
            return httpMessage("超管账户无法使用此接口");
        }

        $balance = POST("balance", "balance");
        $balance = !empty($balance) ? Str::trim($balance) : null;
        if (empty($balance)) {
            return httpMessage("缺少充值资产类型");
        }

        $amount = POST("quantity");
        $amount = is_numeric($amount) && $amount > 0 ? floor($amount) : 0;
        if ($amount <= 0) {
            return httpMessage("充值数额必须大于 0");
        }

        $balanceNames = getFinanceConfig("recharge");
        if (!in_array($balance, array_keys($balanceNames))) {
            return httpMessage("充值资产无效");
        }
        $set = $balanceNames[$balance] ?? [];
        $state = $set["state"] ?? false;
        $price = $set["price"] ?? 0;
        $price = is_numeric($price) && $price > 0 ? $price : 0;
        if ($price <= 0) {
            return httpMessage("未配置充值比例");
        }
        $min = $set["min"] ?? 1;
        $min = is_numeric($min) && $min > 0 ? ceil($min) : 1;
        $max = $set["max"] ?? 0;
        $max = is_numeric($max) && $max > 0 ? $max : 0;

        if (!$state) {
            return httpMessage("此账户资产禁止充值");
        }

        if ($amount < $min) {
            return httpMessage("最小充值数额为：{$min}");
        }

        if ($amount > $max && $max > 0) {
            return httpMessage("最大充值数额为：{$max}");
        }

        $order = [
            "uid"           => $this->uid,
            "orderId"       => makeOrderId(),
            "balance"       => $balance,
            "price"         => $price,
            "quantity"      => $amount,
            "amount"        => bcmul($price, $amount, 2)
        ];

        $db = RechargeModel::emptyQuery();
        if ($db->insert($order)) {
            return httpMessage(0, "操作成功", [
                "orderType"     => "finance_recharge",
                "orderId"       => $order["orderId"]
            ]);
        }
        return httpMessage("操作失败，请稍后再试");
    }

    /**
     * 获取可充值资产配置
     * @return array
     */
    public function balanceList(): array
    {
        //
        $list = getFinanceConfig("recharge");
        $result = [];
        $names = BalanceModel::names();
        foreach ($list as $key => $item) {
            $item["balance"] = $key;
            $item["balanceName"] = $names[$key];
            $result[] = $item;
        }
        return $result;
    }
}